import axios from 'axios';
import { createStore } from 'vuex';
const store = createStore({
    state() {
        return {
            seller: {},
            goods: [],
            ratings:[],
            // 遮罩层默认不显示
            show: false,
            // 总价
            price: 0,
            // 购物车列表数据
            carList: [],
            imgArr: ['../../../img/car.png', '../../../img/car1.png'],
            img: '../../../img/car.png'

        }
    },
    getters: {},
    mutations: {
        setSeller(state, payload) {
            state.seller = payload.data
        },
        setGoods(state, payload) {
            state.goods = payload.data
        },
        setRating(state,payload){
            state.ratings = payload.data

        },
        // 更新购物车是否展示状态
        showCar(state) {
            state.show = !state.show;
        },
        clearCar(state) {
            state.carList.forEach((item) => {
                item.count = 0;
            })
            state.carList = [];
            state.show = false;
            state.img = state.imgArr[0]

        },

        // 在我们进行点击商品加入购物车的时候，要先判断该商品在购物车列表中是否已经存在，如果存在不在添加
        // 不存在的话则push进去
        setCarList(state, payload) {
            const hasItem = state.carList.findIndex((item) => {
                return item.name == payload.item.name;
            });
            // 当hasItem等于-1的时候说明购物车列表中没有该商品数据则push进入购物车列表中
            if (hasItem == "-1") {
                state.carList.push(payload.item);
            }
            state.img = state.imgArr[1]
        },
        // 购物车列表点击减到一的时候把其从购物车列表中删除
        delList(state, payload) {
            const delIndex = state.carList.findIndex((item) => {

                return item.name == payload.item.name
            });
            if (delIndex != -1) {
                state.carList.splice(delIndex, 1);
            } 
            if(state.carList.length===0){
            state.img = state.imgArr[0]
            }
        }

    },
    actions: {
        // 获取商家列表及商品列表
        async getSeller({ commit }) {
            const { data: { data } } = await axios.get('/api/seller')
            commit('setSeller', {
                data
            })
            console.log(data)
        },
        // 获取商家列表及商品列表
        async getGoods({ commit }) {
            const { data: { data } } = await axios.get('/api/goods')
            commit('setGoods', {
                data
            })
            // console.log(data)
        },
        // 获取评价及商品列表
        async getRating({ commit }) {
            const { data: { data } } = await axios.get('/api/ratings')
            commit('setRating', {
                data
            })
            console.log(data)
        }
    }
})

export default store;